<template>
    <div>
        <!-- 导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="myDialogRoles=true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 列表 -->
            <el-row>
                <el-table :data="rolesList" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-row :class="['dbbottom',i1===0?'dbTop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                                <!-- 一级权限 -->
                                <el-col :span="5">
                                    <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 二级三级权限 -->
                                <el-col :span="19">
                                    <el-row :class="[i2===0?'':'dbTop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                         <!-- 二级 -->
                                        <el-col :span="6">
                                            <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                        <!-- 三级 -->
                                        <el-col :span="18">
                                            <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                        </el-col>
                                    </el-row>
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>
                    <!-- 索引列 -->
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="角色名称" prop="roleName"></el-table-column>
                    <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                    <el-table-column label="操作" width="300px">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showRoles(scope.row.id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-search" @click="removeRolesById(scope.row.id)">删除</el-button>
                            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRight(scope.row)">分配权限</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
        </el-card>
        <!-- 添加角色列表 -->
         <el-dialog title="添加角色" :visible.sync="myDialogRoles" width="50%" @close="addRolesClosed">
           <!-- 内容主体 -->
            <el-form :model="addRoles" :rules="addRolesRules" ref="addRolesRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoles.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoles.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="myDialogRoles=false">取 消</el-button>
                <el-button type="primary" @click="addUserRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改角色 -->
         <el-dialog title="修改角色" :visible.sync="EditMyDialogRoles" width="50%" @close="editRolesClosed">
           <!-- 内容主体 -->
            <el-form :model="editRoles" :rules="editRolesRules" ref="editRolesRef" label-width="80px">
                <el-form-item label="角色名称" >
                    <el-input v-model="editRoles.roleName" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoles.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="EditMyDialogRoles=false">取 消</el-button>
                <el-button type="primary" @click="editUserRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限 -->
        <el-dialog title="分配角色" :visible.sync="editRight" width="50%" @close="setRightClosed">
            <!-- 树形控件 -->
            <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="refKeys" ref="treeRef"></el-tree>
             <span slot="footer" class="dialog-footer">
                <el-button @click="editRight=false">取 消</el-button>
                <el-button type="primary" @click="allSetRight">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default ({
   data(){
       return{
           rolesList:[],
           myDialogRoles:false,
           EditMyDialogRoles:false,
           editRight:false,
           addRoles:{
               roleName:'',
               roleDesc:''
           },
           addRolesRules:{
               roleName:[
                   {required:true,message:'请输入角色名',trigger:'blur'},
                    {min:2,max:10,message:'请长度在2-10字符之间',trigger:'blur'}
               ],
                roleDesc:[
                   {required:false,message:'请输入角色描述',trigger:'blur'},
                    {min:2,max:10,message:'请长度在2-10字符之间',trigger:'blur'}
               ]
           },
           editRoles:{},
           editRolesRules:{
                roleDesc:[
                   {required:false,message:'请输入角色描述',trigger:'blur'},
                    {min:2,max:10,message:'请长度在2-10字符之间',trigger:'blur'}
               ]
           },
           rightList:[],
           treeProps:{
                children: 'children',
                label: 'authName'
           },
           refKeys:[],
           roleId:''
              
       }
   },
   created(){
       this.getRolesList()
   },
   methods:{
      async getRolesList(){
          const {data:res} = await this.$http.get('roles')
          if(res.meta.status!==200){
              return this.$messages.error('获取角色列表失败')
          }
          console.log(res);
          this.rolesList=res.data
       },
       addRolesClosed(){
           this.$refs.addRolesRef.resetFields()
       },
       addUserRoles(){
           this.$refs.addRolesRef.validate(async valid => {
               if(!valid)return
               const {data:res} = await this.$http.post('roles',this.addRoles)
                if(res.meta.status!==201){
                  return this.$message.error('角色添加失败')
                }
                this.myDialogRoles=false
                this.getRolesList()
           })
       },
       async showRoles(id){
           this.EditMyDialogRoles=true
           const {data:res} = await this.$http.get('roles/'+id)
           if(res.meta.status!==200){
               return this.$messages.error('查询id错误')
           }
           this.editRoles=res.data
       },
       editRolesClosed(){
            this.$refs.editRolesRef.resetFields()
       },
       editUserRoles(){
           this.$refs.editRolesRef.validate(async valid => {
                if(!valid)return
              const {data:res} = await this.$http.put('roles/'+this.editRoles.roleId,{
                  roleName:this.editRoles.roleName,
                   roleDesc:this.editRoles.roleDesc 
                })
                console.log(res);
               if(res.meta.status!==200){
                   return this.$messages.error('更新角色失败')
               }
               this.EditMyDialogRoles=false
               this.getRolesList()
           })
       },
       async removeRolesById(id){
           const RolesResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(RolesResult!=='confirm'){
            return this.$message.info('已取消删除')
        }
        const {data:res} = await this.$http.delete('roles/'+id)
        if(res.meta.status!==200){
            return this.$messages.error('删除角色失败')
        }
        this.$message.success('删除角色成功')
        this.getRolesList()
       },
      async removeRightById(role,rightId){
         const confirmRs= await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmRs !=='confirm'){
            return this.$message.info('已取消删除')
        }
        const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status!==200){
            return this.$messages.error('删除权限失败')
        }
        role.children=res.data
       },
      async setRight(role){
          this.roleId=role.id
           this.editRight=true
         const {data:res} = await this.$http.get('rights/tree')
         if(res.meta.status!==200){
             return this.$messages.error('获取权限列表失败')
         }
         this.rightList=res.data
         console.log(this.rightList);
         this.getLifKeys(role,this.refKeys)
       },
       getLifKeys(node,arr){
           if(!node.children){
               return arr.push(node.id)
           }
           node.children.forEach(item => {
               this.getLifKeys(item,arr)
           });
       },
       setRightClosed(){
           this.refKeys=[]
       },
      async allSetRight(){
           const keys=[
               ...this.$refs.treeRef.getCheckedKeys(),
               ...this.$refs.treeRef.getHalfCheckedKeys()
           ]
           const isStr =keys.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
               rids:isStr
           })
           if(res.meta.status!==200){
               return this.$messages.error('权限更新错误')
           }
           this.editRight=false
           this.getRolesList()
       }
   }
})
</script>

<style lang="less" scoped>

</style>
